<?php

class ExecScript
{
    /**
     * 脚本位置配置
     * @var array
     */
    public $config=array(
        "lt_cms"=>array(
            "alpha"=>"AlphaScript",
            "release"=>"ReleaseScript",
        ),
    );

    /**
     * 安装脚本
     */
    public function install($versionInfo=array()){
        //判断当前版本
        $versionData=$versionInfo?$versionInfo:app("L_Common_version")->currentInfo();
        if(isset($versionData["project"])){
            $class=isset($this->config[$versionData["project"]][$versionData["stage"]])?$this->config[$versionData["project"]][$versionData["stage"]]:"";
            $this->loadClass($class);
            if(class_exists($class)){
                $version=str_replace(".","",$versionData["version"]);
                $method="version_".$version;
                $obj=new $class();
                if(method_exists($obj,"boot")){
                    $obj->boot();
                }
                if(method_exists($obj,$method)){
                    $obj->$method();
                }
            }
        }
        return true;
    }

    /**
     * 执行脚本
     */
    public function exec($method){
        //判断当前版本
        $versionData=app("L_Common_version")->currentInfo();
        if(isset($versionData["project"])){
            $class=isset($this->config[$versionData["project"]][$versionData["stage"]])?$this->config[$versionData["project"]][$versionData["stage"]]:"";
            $this->loadClass($class);
            if(class_exists($class)){
                $obj=new $class();
                if(method_exists($obj,$method)){
                    return $obj->$method();
                }
            }
        }
        return false;
    }

    /**
     * 获取方法名
     */
    public function getMethods($versionInfo=array()){
        $result=array();
        $versionData=$versionInfo?$versionInfo:app("L_Common_version")->currentInfo();
        if(isset($versionData["project"])){
            $className=isset($this->config[$versionData["project"]][$versionData["stage"]])?$this->config[$versionData["project"]][$versionData["stage"]]:"";
            $this->loadClass($className);
            if(class_exists($className)){
                $class = new \ReflectionClass($className);
                $methods = $class->getMethods();
                foreach ($methods as $method) {
                    if($method->class==$className){
                        $result[]=$method->getName();
                    }
                }
            }
        }
        return $result;
    }

    /**
     * 加载类
     * @param $name
     */
    public function loadClass($name){
        $execScript=LTCMS_ROOT."/version/{$name}.php";
        if(is_file($execScript)){
            include_once $execScript;
        }
    }
}